#$## This script will create a spatial prediction of under log maximum temperature for a single day
#### The day parameter is defined by the submission script

# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}
	
# Establish directories
# NB BRT Source Functions must be located in the working directory

in.dir = '/home1/99/jc152199/brt/underlog/optimalmodelnologvars/'
setwd(in.dir)
maxout.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/ulbrtpreds/max/'

# Load the gbm library to perform Boosted Regression Tree Analysis

library('gbm')
library('SDMTools')

# Load source code for BRT functions

source('brt.functions.R.cjsedit.r')

# Load BRT models

load('/home1/99/jc152199/brt/underlog/optimalmodelnologvars/ULModel.Rdata') ### Object will be called brt.gbm.step

# Needs to include the changing tmax and tmin file

var.names = c(brt.gbm.step$var.names)

# Names of all ASCII files to be read in (in the same order as var.names)

tobescanned = c(tmax.file,tmin.file)

# This loop scans in each ASCII file (skipping the first 6 lines) and assigns it a name based on the vector 'variable.names'

predict.data = NULL

for(i in c(1:2))
	
	{
	
	assign(var.names[i],scan(tobescanned[i], skip=6, na.string = "-9999"),pos=1)
	
	cat(var.names[i],'\n')

	}
	
#### Create the BRTairRange ASCII 

BRTairRange = BRTairmax - BRTairmin

# Bind all the grid data into a single dataframe
	
predict.data = data.frame(BRTairmax,BRTairmin,BRTairRange)
	
# Run the spatial prediction function

gbm.predict.grids(brt.gbm.step, predict.data, want.grids = T, sp.name = paste('tmax.',substr(tmax.file,96,103),sep=''),pred.vec = rep(-9999,1757400), filepath = paste(maxout.dir,substr(tmax.file,96,99),'/',sep=''), num.col = 1010, num.row = 1740, xll = 144.71, yll = -19.77151, cell.size = 0.0025, no.data = -9999)

# Read in the spatial predictions

tmax.asc = read.asc(paste(maxout.dir,substr(tmax.file,96,99),'/','tmax.',substr(tmax.file,96,103),'.asc',sep='')) # Read in ASCII prediction

# Convert spatial predictions to .asc.gz to save space

write.asc.gz(tmax.asc, file=paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/ulbrtpreds/maxgzip/',substr(tmax.file,96,99),'/','tmax.',substr(tmax.file,96,103),sep='')) # Write gzip file of ASCII prediction

# Remove the original .asc versions of the spatial preds

if (file.exists(paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/ulbrtpreds/maxgzip/',substr(tmax.file,96,99),'/','tmax.',substr(tmax.file,96,103),'.asc.gz',sep='')))
{system(paste('rm ',maxout.dir,substr(tmax.file,96,99),'/','tmax.',substr(tmax.file,96,103),'.asc',sep=''))}

# Done
################################################################
